"use strict";

const { Controller } = require('egg');
const moment = require('moment');
const path = require('path');
const fs = require('mz/fs');
const pump = require('mz-modules/pump');
const sd = require('silly-datetime');
const mkdirp = require('mz-modules/mkdirp');
const compressing = require('compressing');

const sendToWormhole = require('stream-wormhole')
const toArray = require('stream-to-array')
/*
上传文件  并记录一个模块

子进程去抓取页面是否有错误标识 

有错误就删除刚上传的模块

*/
function emptyDir(path) {
  const files = fs.readdirSync(path);
  files.forEach(file => {
      const filePath = `${path}/${file}`;
      const stats = fs.statSync(filePath);
      if (stats.isDirectory()) {
          emptyDir(filePath);
      } else {
          fs.unlinkSync(filePath);
          // console.log(`删除${file}文件成功`);
      }
  });
}

class HomeController extends Controller {
  async index() {
    this.ctx.body = { data:'ok' };
  }
  async remove() {
    const  {path } = Object.assign({},this.ctx.query,this.ctx.request.body)
    emptyDir('F:/eggjs-vite-package-share/vite/src/views/' + path)
    this.ctx.body = { data:'ok', path  };
  }

  async upload1() {
    const { ctx } = this;
    const body = ctx.request.body;
    const files = ctx.request.files;
    console.log(files)
    try {
      for (let file of files) {
        const filename = file.filename;
        console.log(filename)
        const targetPath = path.join('app/public/upload', filename);
        // 读取文件
        const source = fs.createReadStream(file.filepath);
        // 创建写入流
        const target = fs.createWriteStream(targetPath);
        await pump(source,target);
      }
    } finally {
      await ctx.cleanupRequestFiles();
    }
    ctx.body = {
      body, files
    }
  }

  
  async upload() {
    const { ctx } = this;
    const body = ctx.request.body;
   //const files = ctx.request.files;
    
    try {
     
       
      const parts = await ctx.multipart()
      console.log(parts)
      let part;
      let data = []
      while ((part = await parts()) != null) {
        if (part.length) {
          console.log("do push")
          // 新增一个对象，field就是key名，data就是上传的数据，压入data对象数组中。
          data.push({
            field: part[0].replace(/ /g, ''),
            data: part[1]
          })
          

        } else {
          // 转成buffer数组
          const partData = await toArray(part).then(
            function (parts) {
              const buffers = []
              for (let i = 0, l = parts.length; i < l; ++i) {
                const part = parts[i]
                buffers.push((part instanceof Buffer) ? part : new Buffer(part))
              }
              return Buffer.concat(buffers)
            }
          )
          compressing.zip.uncompress(partData, `F:/eggjs-vite-package-share/vite/src/views`).then(data => {
            console.log(data);
            let message = "Zip文件上传并解压成功！"
            console.log(message)
        }).catch(err => {
            let message = "Zip文件上传并解压失败！" 
            console.log(message)
            console.log(err);
        })
          
        }
      }

     

    } finally {
      await ctx.cleanupRequestFiles();
    }
    ctx.body = {
      body
    }
  }
   
}

module.exports = HomeController;
